package iconSwingStates;

import fr.emn.inputeditor.JInputEditor;
import fr.emn.reactiveinput.Configuration;
import fr.emn.reactiveinput.DeviceFolder;
import fr.emn.reactiveinput.OpenContext;
import fr.emn.reactiveinput.devices.FRoot;
import fr.lri.swingstates.canvas.Canvas;
import iconSwingStates.Device.DSwingStatesDevice;
import iconSwingStates.StateMachine.SMIconStateMachine;

import java.io.File;

import javax.swing.JFrame;

/**
 * LIConLauncher is the class that starts ICon without needing any action from the developer.
 * @author uribe-gaget
 *
 */
public class LIConLauncher {
	/**
	 * The unique instance
	 */
	private static LIConLauncher instance;
	/**
	 * The folder where the devices are put into.
	 */
	private static FSwFolder folder;
	/**
	 * The default configuration file
	 */
	private final File confFile = new File("default.ic");
	private JInputEditor dialog;
	/**
	 * The configuration of ICon
	 */
	private static Configuration conf;

	/** Get the unique instance of LIConLauncher<p>
	 * Note : the constructor is became unreachable.
	 */
	public static LIConLauncher start(String name, JFrame frame, Canvas canvas, SMIconStateMachine sm) {
		if (null == instance) { 
			instance = new LIConLauncher(name, frame, canvas, sm);
		}
		else{
			folder.add(new DSwingStatesDevice(name, sm));
			conf.add(new DSwingStatesDevice(name, sm));
			folder.refresh();

		}
		return instance;
	}

	/**
	 * Private constructor in order to force the use of the start method
	 * @param name The name of the state machine
	 * @param frame The frame of the application
	 * @param canvas The canvas of the state machine
	 * @param sm The state machine
	 */
	private LIConLauncher(String name, JFrame frame, Canvas canvas, SMIconStateMachine sm) {
		// ** CREATE AND RUN CONFIGURATION **           
		folder = new FSwFolder("Application Devices");
		folder.add(new DSwingStatesDevice(name, sm));
		// [1] Create IconDraw Device Folder
		DeviceFolder root = new FRoot(folder);
		// [2] Create a new empty configuration
		OpenContext context = new OpenContext(frame);
		context.setValue("OBJECT", canvas);
		conf = new Configuration(context, root);
		// [3] Try to load configuration from a file
		//conf.load(confFile);
		dialog = new JInputEditor(conf);
		if (conf != null) {
			// [4] Open configuration
			conf.open();
			// [5] Start configuration
			conf.start();
		}
	}


}